<template>
  <div class="wards-management">
    <div class="header">
      <h2>病房管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加病房
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="病房编号、病房名称"
            clearable
            @clear="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="科室">
          <el-tree-select
            v-model="searchForm.departmentId"
            placeholder="请选择科室"
            clearable
            filterable
            :data="departmentTree"
            node-key="id"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children'
            }"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="病房类型" >
          <el-select v-model="searchForm.type" clearable filterable placeholder="请选择类型" >
            <el-option label="全部" value="" />
            <el-option label="普通病房" :value="1" />
            <el-option label="重症监护" :value="2" />
            <el-option label="手术室" :value="3" />
            <el-option label="产房" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status"  clearable filterable placeholder="请选择状态" >
            <el-option label="全部" value="" />
            <el-option label="停用" :value="0" />
            <el-option label="启用" :value="1" />
            <el-option label="维修中" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层">
          <el-input-number
            v-model="searchForm.floor"
            :min="1"
            :max="50"
            placeholder="楼层"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.total }}</div>
            <div class="stat-label">总病房数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.totalBeds }}</div>
            <div class="stat-label">总床位数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.occupiedBeds }}</div>
            <div class="stat-label">已占用床位</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.occupancyRate }}%</div>
            <div class="stat-label">床位使用率</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 病房列表 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column prop="wardNo" label="病房编号" width="120" />
      <el-table-column prop="name" label="病房名称" width="150" />
      <el-table-column prop="departmentName" label="科室" width="120" />
      <el-table-column prop="type" label="病房类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="floor" label="楼层" width="80">
        <template #default="{ row }">
          {{ row.floor }}F
        </template>
      </el-table-column>
      <el-table-column prop="location" label="位置" width="150" />
      <el-table-column label="床位情况" width="150">
        <template #default="{ row }">
          <div class="bed-info">
            <span class="bed-occupied">{{ row.occupiedBeds }}</span>
            /
            <span class="bed-total">{{ row.totalBeds }}</span>
            <el-progress
              :percentage="getBedOccupancyRate(row)"
              :status="getBedProgressStatus(row)"
              :stroke-width="6"
              style="margin-top: 4px"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="nurseName" label="负责护士" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="equipment" label="设备信息" min-width="150" show-overflow-tooltip />
      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            <el-icon><View /></el-icon>
            详情
          </el-button>
          <el-button type="warning" size="small" @click="handleEditBeds(row)">
            <el-icon><Edit /></el-icon>
            床位
          </el-button>
          <el-button type="success" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="danger"
            size="small"
            @click="handleUpdateStatus(row, 0)"
          >
            停用
          </el-button>
          <el-button
            v-else
            type="info"
            size="small"
            @click="handleUpdateStatus(row, 1)"
          >
            启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, View, Edit } from '@element-plus/icons-vue'
import { getWardList, getWardDetail, updateWard, addWard, getNurseList } from '@/api/business'
import { getDepartmentTree } from '@/api/business'
import { addDialog } from '@/components/gDialog/index'
import wardHandle from '@/views/adminModal/wardHandle.vue'
import bedManageHandle from '@/views/adminModal/bedManageHandle.vue'
import wardDetailHandle from '@/views/adminModal/wardDetailHandle.vue'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const tableData = ref([])
const selectedWard = ref(null)
const departmentTree = ref([])
const wardList = ref([])
const nurseList = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  departmentId: null,
  type: '',
  status: '',
  floor: null
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 统计数据
const statistics = computed(() => {
  const total = tableData.value.length
  const totalBeds = tableData.value.reduce((sum, ward) => sum + (ward.totalBeds || 0), 0)
  const occupiedBeds = tableData.value.reduce((sum, ward) => sum + (ward.occupiedBeds || 0), 0)
  const occupancyRate = totalBeds > 0 ? Math.round((occupiedBeds / totalBeds) * 100) : 0
  
  return { total, totalBeds, occupiedBeds, occupancyRate }
})

// 页面加载时获取数据
onMounted(() => {
  getDepartmentTreeData()
  handleSearch()
  fetchNurses()
})

// 获取科室树形数据
const getDepartmentTreeData = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
  }
}

// 获取病房列表
const fetchWards = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getWardList(params)
    
    if (response.code === 200) {
      // 填充科室名称
      const wards = response.data || []
      await fillDepartmentNames(wards)
      tableData.value = wards
      pagination.total = wards.length
    } else {
      ElMessage.error(response.message || '获取病房列表失败')
    }
  } catch (error) {
    console.error('获取病房列表失败:', error)
    ElMessage.error('获取病房列表失败')
  } finally {
    loading.value = false
  }
}

// 获取护士列表
const fetchNurses = async () => {
  try {
    const response = await getNurseList({ role: 2 }) // 假设护士角色为2
    if (response.code === 200) {
      if (Array.isArray(response.data)) {
        nurseList.value = response.data
      } else {
        nurseList.value = response.data.list || []
      }
    }
  } catch (error) {
    console.error('获取护士列表失败:', error)
  }
}

// 填充科室名称
const fillDepartmentNames = async (wards) => {
  const departmentMap = {}
  departmentTree.value.forEach(dept => {
    departmentMap[dept.id] = dept.name
  })
  
  wards.forEach(ward => {
    if (ward.departmentId && departmentMap[ward.departmentId]) {
      ward.departmentName = departmentMap[ward.departmentId]
    }
  })
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchWards()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    departmentId: null,
    type: '',
    status: '',
    floor: null
  })
  pagination.page = 1
  fetchWards()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchWards()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchWards()
}

// 添加病房
const handleAdd = () => {
  addDialog({
    title: '添加病房',
    component: wardHandle,
    width: '800px',
    props: {
      wardData: {},
      isEdit: false,
      departmentList: departmentTree.value,
      nurseList: nurseList.value
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchWards()
      }
    }
  })
}

// 编辑病房
const handleEdit = (row) => {
  addDialog({
    title: '编辑病房',
    component: wardHandle,
    width: '800px',
    props: {
      wardData: row,
      isEdit: true,
      departmentList: departmentTree.value,
      nurseList: nurseList.value
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchWards()
      }
    }
  })
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await getWardDetail(row.id)
    if (response.code === 200) {
      addDialog({
        title: '病房详情',
        component: wardDetailHandle,
        width: '700px',
        props: {
          wardData: response.data
        }
      })
    } else {
      ElMessage.error(response.message || '获取病房详情失败')
    }
  } catch (error) {
    console.error('获取病房详情失败:', error)
    ElMessage.error('获取病房详情失败')
  }
}

// 床位管理
const handleEditBeds = (row) => {
  addDialog({
    title: '床位管理',
    component: bedManageHandle,
    width: '600px',
    props: {
      wardData: row
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchWards()
      }
    }
  })
}

// 更新状态
const handleUpdateStatus = async (row, newStatus) => {
  const statusText = getStatusText(newStatus)
  
  try {
    await ElMessageBox.confirm(
      `确定要将病房"${row.name}"${newStatus === 0 ? '停用' : '启用'}吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await updateWard({
      ...row,
      status: newStatus
    })

    if (response.code === 200) {
      ElMessage.success(`病房${newStatus === 0 ? '停用' : '启用'}成功`)
      fetchWards()
    } else {
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态更新失败:', error)
      ElMessage.error('状态更新失败')
    }
  }
}

// 获取床位使用率
const getBedOccupancyRate = (ward) => {
  if (!ward.totalBeds || ward.totalBeds === 0) return 0
  return Math.round((ward.occupiedBeds / ward.totalBeds) * 100)
}

// 获取床位进度条状态
const getBedProgressStatus = (ward) => {
  const rate = getBedOccupancyRate(ward)
  if (rate >= 90) return 'exception'
  if (rate >= 80) return 'warning'
  return 'success'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '停用',
    1: '启用',
    2: '维修中'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',
    1: 'success',
    2: 'warning'
  }
  return typeMap[status] || 'info'
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '普通病房',
    2: '重症监护',
    3: '手术室',
    4: '产房'
  }
  return typeMap[type] || '未知'
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'primary',
    2: 'danger',
    3: 'warning',
    4: 'success'
  }
  return typeMap[type] || 'info'
}
</script>

<style scoped>
.wards-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.bed-info {
  text-align: center;
}

.bed-occupied {
  color: #e6a23c;
  font-weight: bold;
}

.bed-total {
  color: #409eff;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.bed-management {
  padding: 20px 0;
}

.ward-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.ward-info p {
  margin: 0 0 20px 0;
  color: #606266;
}

.occupancy-rate {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.detail-content {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 20px 20px 10px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-progress-bar__outer) {
  background-color: #f0f2f5;
}
</style>